import _ from 'love-u'
import config from './config'
import { $getToken, $clearLoginInfo, $getCache } from './storage'
import { $redirect2Login } from './router'
import { $msg } from './message'


function $request({ method, url, needAuth, header, data, responseType = 'text' }) {
	return new Promise((resolve, reject) => {
		let endUrl = url
		if (!url.startsWith("http")) url = config.BASE_API + url;
		if (config.NODE_ENV === 'development')
			console.log("simba:访问了" + url);
		header = header || {};
		// 需要传token去识别身份
		if (needAuth) {
			let access_token = $getToken();
			if (access_token) {
				header[config.KEY_TOKEN] = access_token;
				header["token"] = $getCache("token");
			} else {
				return $msg("请先登录", () => {
					$clearLoginInfo()
					resolve({ success: false });
					$redirect2Login();
				});
			}
		}

		uni.request({
			method,
			url,
			data,
			header,
			timeout: 5000,
			responseType,
			success: ({ data, statusCode }) => {
				if (!data) data = { errorCode: 200, data: null, message: "" };
				//网络500
				if (statusCode === 200) resolve(data);
				else if (statusCode === 401) {
					// resolve({ msg: "登录信息已过期，请重新登录", success: false });
					// $clearLoginInfo()
					// $redirect2Login();
					$msg("请求繁忙，请稍后重试", () => {
						reject({ success: false });
						// $clearLoginInfo()
						// $redirect2Login();
					});
				} else reject(statusCode);
				//业务系统500
				switch (data.code) {
					case 500:
						// $msg(data.message || "网络异常,请稍后再试");
						reject(data.code);
						break;
					case 4001:
					case 40001:
					case 401:
						$msg("请求繁忙，请稍后重试", () => {
							reject({ success: false });
							// $clearLoginInfo()
							// $redirect2Login();
						});
				}
			},
			fail: (err) => {
				console.log("接口出错", err);
				reject(err);
			},
		});
	});
}

export function $get(url, data, needAuth = true) {
	return $request({ method: "GET", url, data, needAuth, });
}

//将参数放到路径中
export function $postQ(url, data, needAuth = true) {
	let qs = _.convertObj2Str(data);
	if (qs) url += "?" + qs;
	return $request({ method: "POST", url, needAuth });
}

//将参数放到body中
export function $postB(url, data, needAuth = true) {
	return $request({ method: "POST", url, data, needAuth });
}

//将参数放到form中
export function $postF(url, data, needAuth = true) {
	return $request({
		method: "POST",
		url,
		data,
		needAuth,
		header: {
			"content-type": "application/x-www-form-urlencoded",
		},
	});
}

export function $put(url, data, needAuth = true) {
	return $request({
		method: "PUT",
		url,
		data,
		needAuth,
	});
}

export function $del(url, data, needAuth = true) {
	return $request({
		method: "DELETE",
		url,
		data,
		needAuth,
	});
}

export function $upload({
	filePath,
	needAudit,
	url = config.UPLOAD_URL,
	name = 'file',
	formData
}) {
	return new Promise((resolve, reject) => {
		url += '?needAudit=' + +needAudit
		uni.uploadFile({
			url,
			filePath,
			name,
			header: {
				[config.KEY_TOKEN]: $getToken(),
			},
			formData,
			complete: ({ data }) => {
				try {
					if (typeof data === "string") data = JSON.parse(data);
					resolve(data);
				} catch (e) {
					resolve(null);
				}
			},
			fail: (res) => {
				$msg("上传失败");
				reject(res)
			},
		});
	});
}

export async function $exportExcel({
	method = 'GET',
	url,
	data,
	fileName = ''
}) {
	try {
		uni.showLoading({})
		let data1 = await $request({ method, url, needAuth: true, data, responseType: "arraybuffer" })
		let fm = wx.getFileSystemManager()
		fileName += +new Date
		let filePath = `${wx.env.USER_DATA_PATH}/${fileName}.xlsx`
		fm.writeFile({
			filePath,
			data: data1,
			success: () => {
				uni.openDocument({
					filePath,
					fail: (e) => {
						console.log(e);
						this.$msg("文件打开失败")
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			fail: (e) => {
				console.log(e);
				this.$msg("文件保存失败")
				uni.hideLoading()
			}
		})
	} catch (e) {
		uni.hideLoading()
	}
}

export function $log(content) {
	try {
		$postB('https://simbajs.com:7003/system/log', {
			platform: "小飞信",
			content: JSON.stringify(content)
		})
	} catch (e) {

	} finally {
		return true
	}
}